package com.wxy.customview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

/**
 * 点赞View
 * @author wxy
 *
 * 测量：
 *     wrap--> 宽度 =  Max（上部点的宽度,下面图片的宽度）
 *
 * 动画:
 *      未点赞状态 --> 直接显示未选中图片
 *      点赞状态   --> 将未选中图片缩小  --> 将选中图片放大
 *
 * 绘制：
 *      扩散圆圈效果 --> 裁剪canvas 绘制上半部图片
 *
 */
public class ThumbupView extends View implements View.OnClickListener {
    private static final String TAG = "ThumbupView";
    //圆圈颜色
    private static final int START_COLOR = Color.parseColor("#00e24d3d");
    private static final int END_COLOR = Color.parseColor("#88e24d3d");
    //缩放动画的时间
    private static final int SCALE_DURING = 150;
    //圆圈扩散动画的时间
    private static final int RADIUS_DURING = 100;

    private static final float SCALE_MIN = 0.9f;
    private static final float SCALE_MAX = 1f;

    private Bitmap mThumbUp;
    private Bitmap mSelectDotBitmap;
    private Bitmap mThumbNormal;
    private Paint mBitmapPaint;
    private int mThumbWidth;
    private int mThumbHeight;
    private int mDotWidth;
    private int mDotHeight;
    private TuvPoint mDotPoint;
    private TuvPoint mThumbPoint;
    private TuvPoint mCirclePoint;
    private Paint mCirclePaint;
    private Path mClipPath;
    private float mMaxRadius;
    private float mMinRadius;
    private float mRadius;
    private boolean mIsThumbUp;
    private AnimatorSet mThumbUpAnim;
    private AnimatorSet mThumbDownAnim;

    public ThumbupView(Context context) {
        this(context, null);
    }

    public ThumbupView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public ThumbupView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        setOnClickListener(this);
    }

    private void init() {
        initBitmapInfo();

        //圆环
        mCirclePaint = new Paint();
        mCirclePaint.setAntiAlias(true);
        mCirclePaint.setStyle(Paint.Style.STROKE);
        mCirclePaint.setStrokeWidth(TuvUtils.dip2px(getContext(), 2));

        mCirclePoint = new TuvPoint();
        mCirclePoint.x = mThumbPoint.x + mThumbWidth / 2;
        mCirclePoint.y = mThumbPoint.y + mThumbHeight / 2;

        mMaxRadius = Math.max(mCirclePoint.x - getPaddingLeft(), mCirclePoint.getY() - getPaddingTop());
        mMinRadius = TuvUtils.dip2px(getContext(), 8);
        mClipPath = new Path();
        mClipPath.addCircle(mCirclePoint.x, mCirclePoint.y, mMaxRadius, Path.Direction.CW);
    }

    private void initBitmapInfo() {
        mBitmapPaint = new Paint();
        mBitmapPaint.setAntiAlias(true);

        resetBitmap();

        mThumbWidth = mThumbUp.getWidth();
        mThumbHeight = mThumbUp.getHeight();

        mDotWidth = mSelectDotBitmap.getWidth();
        mDotHeight = mSelectDotBitmap.getHeight();

        //计算起点位置
        mDotPoint = new TuvPoint();
        mDotPoint.x = getPaddingLeft() + TuvUtils.dip2px(getContext(), 2);
        mDotPoint.y = getPaddingTop();

        mThumbPoint = new TuvPoint();
        mThumbPoint.x = getPaddingLeft();
        mThumbPoint.y = getPaddingTop() + TuvUtils.dip2px(getContext(), 8);
    }

    private void resetBitmap() {
        mThumbUp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_messages_like_selected);
        mSelectDotBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_messages_like_selected_shining);
        mThumbNormal = BitmapFactory.decodeResource(getResources(), R.drawable.ic_messages_like_unselected);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(TuvUtils.getDefaultSize(widthMeasureSpec, getContentWidth() + getPaddingLeft() + getPaddingRight()),
                TuvUtils.getDefaultSize(heightMeasureSpec, getContentHeight() + getPaddingTop() + getPaddingBottom()));
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mIsThumbUp) {
            canvas.save();
            canvas.clipPath(mClipPath);
            canvas.drawBitmap(mSelectDotBitmap, mDotPoint.x, mDotPoint.y, mBitmapPaint);
            canvas.restore();
            canvas.drawCircle(mCirclePoint.x, mCirclePoint.y, mRadius, mCirclePaint);

            canvas.drawBitmap(mThumbUp, mThumbPoint.x, mThumbPoint.y, mBitmapPaint);
        } else {
            canvas.drawBitmap(mThumbNormal, mThumbPoint.x, mThumbPoint.y, mBitmapPaint);
        }
    }

    public int getContentWidth() {
        float minLeft = Math.min(mDotPoint.x, mThumbPoint.x);
        float maxRight = Math.max(mDotPoint.x + mDotWidth, mThumbPoint.x + mThumbWidth);
        return (int) (maxRight - minLeft);
    }

    public int getContentHeight() {
        float minTop = Math.min(mDotPoint.y, mThumbPoint.y);
        float maxBottom = Math.max(mDotPoint.y + mDotHeight, mThumbPoint.y + mThumbHeight);
        return (int) (maxBottom - minTop);
    }

    @Override
    public void onClick(View view) {
//        Toast.makeText(getContext(), "onClick-->", Toast.LENGTH_SHORT).show();
//        Log.e(TAG, "width-->" + getContentWidth());
//        Log.e(TAG, "height-->" + getContentHeight());
//        Log.e(TAG, "circle-->" + mCirclePoint);
        startAnim();
    }

    public void startAnim() {
        if (mIsThumbUp) {
            startThumbDownAnim();
        } else {
            startThumbUpAnim();
        }
    }

    private void startThumbUpAnim() {
        ObjectAnimator thumbNormalScale = ObjectAnimator.ofFloat(this, "ThumbNormalScale", SCALE_MAX, SCALE_MIN);
        thumbNormalScale.setDuration(SCALE_DURING);
        thumbNormalScale.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mIsThumbUp = true;

            }
        });

        ObjectAnimator thumbUpScale = ObjectAnimator.ofFloat(this, "ThumbScale", SCALE_MIN, SCALE_MAX);
        thumbUpScale.setDuration(SCALE_DURING);
        thumbUpScale.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
            }
        });

        ObjectAnimator circleScale = ObjectAnimator.ofFloat(this, "CircleScale", mMinRadius, mMaxRadius);
        circleScale.setDuration(RADIUS_DURING);

        mThumbUpAnim = new AnimatorSet();
        mThumbUpAnim.play(thumbUpScale).with(circleScale);
        mThumbUpAnim.play(thumbUpScale).after(thumbNormalScale);
        mThumbUpAnim.start();
    }

    private void startThumbDownAnim() {
        ObjectAnimator thumbNormalScale = ObjectAnimator.ofFloat(this, "ThumbNormalScale", SCALE_MIN, SCALE_MAX);
        thumbNormalScale.setDuration(SCALE_DURING);
        thumbNormalScale.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mIsThumbUp = false;

            }
        });

//        ObjectAnimator thumbUpScale = ObjectAnimator.ofFloat(this, "ThumbScale", SCALE_MAX, SCALE_MIN);
//        thumbUpScale.setDuration(SCALE_DURING);
//        thumbUpScale.addListener(new AnimatorListenerAdapter() {
//            @Override
//            public void onAnimationEnd(Animator animation) {
//                super.onAnimationEnd(animation);
//            }
//        });

        mThumbDownAnim = new AnimatorSet();
        mThumbDownAnim.play(thumbNormalScale);
        mThumbDownAnim.start();
    }

    public void setThumbNormalScale(float scale) {
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        mThumbNormal = BitmapFactory.decodeResource(getResources(), R.drawable.ic_messages_like_unselected);
        mThumbNormal = Bitmap.createBitmap(mThumbNormal, 0, 0, mThumbNormal.getWidth(), mThumbNormal.getHeight(),
                matrix, true);
        postInvalidate();
    }

    public void setThumbScale(float scale) {
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        mThumbUp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_messages_like_selected);
        mThumbUp = Bitmap.createBitmap(mThumbUp, 0, 0, mThumbUp.getWidth(), mThumbUp.getHeight(),
                matrix, true);
        postInvalidate();
    }

    public TuvPoint getCirclePoint() {
        return mCirclePoint;
    }

    /**
     * 设置圆环 大小 和 颜色
     *
     * @param scale 进度值
     */
    public void setCircleScale(float scale) {
        mRadius = scale;
        mClipPath = new Path();
        mClipPath.addCircle(mCirclePoint.x, mCirclePoint.y, mRadius, Path.Direction.CW);
        float faction = (mMaxRadius - mRadius) / (mMaxRadius - mMinRadius);
        mCirclePaint.setColor((int) TuvUtils.evaluate(faction, START_COLOR, END_COLOR));
        postInvalidate();
    }
}
